﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DoeObjects;
using DoeLibsMVC.Models;

namespace DoeLibsMVC.Controllers.api
{
    public class AuthorController : ApiController
    {
        /// <summary>
        /// returns all authors or searches by name
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public List<AuthorModel> Get(string q = null)
        {
            List<Author> authors = null;
            if (string.IsNullOrEmpty(q))
            {
                authors = Author.getAll();
            }
            else
            {
                authors = new List<Author>();
                authors = Author.getByName(q, true);

                authors = authors.Distinct().ToList();
            }

            List<AuthorModel> models = new List<AuthorModel>();

            foreach (Author author in authors)
            {
                AuthorModel am = new AuthorModel();
                am.Author = author;
                am.Titles = Title.getTitlesFromAuthor(author.Aid);

                models.Add(am);
            }

            return models;
        }

        /// <summary>
        /// returns information about an author
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public HttpResponseMessage Get(int id)
        {
            Author author = Author.getByAid(id);
            if (author == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            AuthorModel am = new AuthorModel();
            am.Author = author;
            am.Titles = Title.getTitlesFromAuthor(id);

            return Request.CreateResponse<AuthorModel>(HttpStatusCode.OK, am);
        }

        /// <summary>
        /// edit an author
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [DoeLibsMVC.Filter.ValidateModel]
        [Security.BasicAuthorize(Roles = Security.UserCategoryHelper.STAFF_CATEGORY)]
        public HttpResponseMessage Put(int id, EditAuthorModel model)
        {
            Author author = Author.getByAid(id);

            if (author != null)
            {
                author.Name = model.Name;

                if (author.save())
                {
                    return Request.CreateResponse(HttpStatusCode.OK);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError);
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
        }
    }
}
